import 'dart:math';

import 'package:casdon/common/utils/string_externtion.dart';
import 'package:casdon/common/widget/common_banner_widget.dart';
import 'package:casdon/common/widget/common_loading_widget.dart';
import 'package:casdon/common/widget/common_sliver_grid.dart';
import 'package:casdon/common/widget/common_sliver_list_widget.dart';
import 'package:casdon/core/logger/log.dart';
import 'package:casdon/core/utils/list_externtion.dart';
import 'package:casdon/modules/recipe/application/notification/recipe_banner_list_notifier.dart';
import 'package:casdon/modules/recipe/application/notification/recipe_category_notifier.dart';
import 'package:casdon/modules/recipe/application/notification/recipe_module_list_notifier.dart';
import 'package:casdon/modules/recipe/application/notification/recipe_today_list_notifier.dart';
import 'package:casdon/modules/recipe/data/model/recipe_category_model.dart';
import 'package:casdon/modules/recipe/data/model/recipe_today_model.dart';
import 'package:casdon/modules/recipe/providers/recipe_provider.dart';
import 'package:casdon/modules/recipe/ui/widgets/Recipe_card_item.dart';
import 'package:casdon/modules/recipe/ui/widgets/recipe_category_item.dart';
import 'package:casdon/modules/recipe/ui/widgets/recipe_module_section.dart';
import 'package:casdon/modules/recipe/ui/widgets/single_select_tab.dart';
import 'package:casdon/auto_router.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

// 精选菜谱
class RecipeCuratedScreen extends ConsumerStatefulWidget {
  final VoidCallback? onRefreshed;

  const RecipeCuratedScreen({super.key, this.onRefreshed});

  @override
  ConsumerState<RecipeCuratedScreen> createState() {
    return _RecipeCuratedState();
  }
}

class _RecipeCuratedState extends ConsumerState<RecipeCuratedScreen> {
  bool _isRefreshing = false;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    final bannerListState = ref.watch(recipeBannerListNotifierProvider);
    final recipecategoryAsyState = ref.watch(recipeCategoryAsyncProvider);
    final recipeCategoryAsyNotifier = ref.watch(
      recipeCategoryAsyncProvider.notifier,
    );

    final recipeModuleListAsyncNotifier = ref.watch(
      recipeModuleListAsyncProvider.notifier,
    );

    final recipeModuleListState = ref.watch(recipeModuleListAsyncProvider);
    final recipeTodayListNotifier = ref.read(
      recipeTodayListAsyncProvider.notifier,
    );
    final recipeTodayListState = ref.watch(recipeTodayListAsyncProvider);

    return NotificationListener<ScrollNotification>(
      onNotification: (notification) {
        if (notification is ScrollEndNotification &&
            notification.metrics.pixels >=
                notification.metrics.maxScrollExtent - 50) {
          recipeTodayListNotifier.loadMore();
        }
        return false;
      },
      child: RefreshIndicator(
        onRefresh: () => _handleRefresh(
          recipeCategoryAsyNotifier,
          recipeModuleListAsyncNotifier,
          recipeTodayListNotifier,
        ),
        child: CustomScrollView(
          slivers: [
            SliverToBoxAdapter(
              child: Container(
                color: Colors.transparent,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    SizedBox(height: 10.h),
                    bannerListState.when(
                      loading: () => const CommonLoadingWidget(),
                      error: (e, _) => const CommonLoadingWidget(),
                      data: (state) {
                        final imgUrls = (state.data ?? [])
                            .map((e) => e.imageSrc.cropParams1000)
                            .toList();
                        final linkUrls = state.data
                            .map((e) => e.linkUrl)
                            .toList();
                        return _buildBanner(
                          imgUrls.takeFirstN(5),
                          linkUrls.takeFirstN(5),
                        );
                      },
                    ),
                  ],
                ),
              ),
            ),
            SliverToBoxAdapter(child: SizedBox(height: 4.h)),
            SliverAsyncListView<RecipeCategoryModel>(
              asyncData: recipecategoryAsyState.whenData((s) => s.data),
              sliverBuilder: (context, data) =>
                  CommonSliverGrid<RecipeCategoryData>(
                    padding: EdgeInsets.only(
                      left: 36.w,
                      right: 36.w,
                      top: 12.w,
                    ),
                    crossAxisCount: 4,
                    items: data.sublist(0, min(8, data.length)),
                    itemBuilder: (context, item, index) {
                      return _buildCategoryItem(
                        context,
                        item,
                        index,
                        onTap: (RecipeCategoryData data) {
                          Log.i("点击了: ${data.title}");
                          if (index == 7) {
                            RecipeCategoryRoute().push(context);
                          } else {
                            // 进入二级页面
                            RecipeCategoryDetailRoute(
                              id: data.id,
                              title: data.title,
                            ).push(context);
                          }
                        },
                      );
                    },
                  ),
            ),

            SliverToBoxAdapter(child: SizedBox(height: 0.h)),

            recipeModuleListState.when(
              loading: () => _buildSliverLoading(),
              error: (e, _) => _buildSliverError(''),
              data: (state) => SliverList(
                delegate: SliverChildBuilderDelegate((context, index) {
                  final module = state.data[index];
                  return RecipeModuleSection(model: module); //
                }, childCount: state.data.length),
              ),
            ),
            // ================ 今日菜谱 ==================//
            SliverToBoxAdapter(
              child: _buildTodayRecommendHeader("今日推荐", context),
            ),

            recipeTodayListState.when(
              loading: () => _buildSliverLoading(),
              error: (e, _) => _buildSliverError(''),
              data: (data) {
                final activeState =
                    data.activeSort == TodayRecipeSortType.createTime
                    ? data.dataHot
                    : data.dataNew;
                final items = activeState.data;
                if (items.isEmpty) {
                  return _buildSliverEmpty('暂无数据');
                }
                return SliverPadding(
                  padding: EdgeInsets.only(left: 12.w, right: 12.w),
                  sliver: SliverGrid(
                    delegate: SliverChildBuilderDelegate((context, index) {
                      return InkWell(
                        borderRadius: BorderRadius.circular(8),
                        onTap: () {
                          RecipeDetailRoute(
                            recipeId: items[index].recipeId,
                            title: items[index].title,
                            isSmart: items[index].isSmart,
                          ).push(context);
                        },
                        child: RecipeCardItem(item: items[index]),
                      );
                    }, childCount: items.length),
                    gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
                      maxCrossAxisExtent: 200.w,
                      mainAxisSpacing: 12.w,
                      crossAxisSpacing: 12.w,
                      mainAxisExtent: 138.h,
                    ),
                  ),
                );
              },
            ), // 其他 Sliver...
          ],
        ),
      ),
    );
  }

  Future<void> _handleRefresh(
    RecipeCategoryNotifier categoryNotifier,
    RecipeModuleListNotifier moduleListNotifier,
    RecipeTodayListNotifier todayListNotifier,
  ) async {
    if (_isRefreshing) return;
    _isRefreshing = true;
    try {
      await Future.wait([
        categoryNotifier.refresh(),
        moduleListNotifier.refresh(),
        todayListNotifier.refresh(),

        ref.read(recipeBannerListNotifierProvider.notifier).refresh(),
      ]);
      widget.onRefreshed?.call();
    } finally {
      _isRefreshing = false;
    }
  }

  // 构建菜谱分类Item
  Widget _buildCategoryItem(
    BuildContext context,
    RecipeCategoryData item,
    int index, {
    void Function(RecipeCategoryData item)? onTap,
  }) {
    RecipeCategoryData newItem = item;

    final state = ref.read(recipeCategoryAsyncProvider);

    // 判断是否是第 8 个，并替换为“全部”
    if ((state.value!.data ?? []).length > 7 && index == 7) {
      newItem = item.placeholder();

      // 如果外部没有传 onTap，则默认点击跳转“菜谱分类页面”
      onTap ??= (RecipeCategoryData item) {
        Log.i("点击了全部，进入菜谱分类页面");
        RecipeCategoryRoute().push(context);
      };
    }

    // 如果是普通 item，使用外部传入的 onTap 或默认打印 imgUrl
    onTap ??= (RecipeCategoryData item) {
      Log.i(item.imgUrl);
    };

    return RecipeCategoryItem(item: newItem, onTap: onTap);
  }

  // ========= 通用状态 Sliver =========
  SliverToBoxAdapter _buildSliverLoading() => const SliverToBoxAdapter(
    child: Padding(
      padding: EdgeInsets.symmetric(vertical: 40),
      child: Center(child: CommonLoadingWidget()),
    ),
  );

  SliverToBoxAdapter _buildSliverError(String message) => SliverToBoxAdapter(
    child: Padding(
      padding: EdgeInsets.symmetric(vertical: 40),
      child: Center(child: Text(message)),
    ),
  );

  SliverToBoxAdapter _buildSliverEmpty(String message) => SliverToBoxAdapter(
    child: Padding(
      padding: EdgeInsets.symmetric(vertical: 40),
      child: Center(
        child: Text(
          message,
          style: TextStyle(fontSize: 14.r, color: Colors.grey),
        ),
      ),
    ),
  );

  Widget _buildTodayRecommendHeader(String title, BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Text(
            title,
            style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w400),
          ),
          SingleSelectTab(
            onChanged: (index) {
              final notifier = ref.read(recipeTodayListAsyncProvider.notifier);
              if (index == 0) {
                notifier.fetchFirstPage(sortType: TodayRecipeSortType.view);
              } else {
                notifier.fetchFirstPage(
                  sortType: TodayRecipeSortType.createTime,
                );
              }
            },
          ),
        ],
      ),
    );
  }

  Widget _buildBanner(List<String> imageUrls, List<String> linkUrls) {
    if (imageUrls.isEmpty) {
      return const SizedBox.shrink();
    }
    return CommonBannerWidget(
      imageUrls: imageUrls,
      height: 148.h,
      onTap: (index) {
        if (index < 0 || index >= linkUrls.length) return;
        final urlStr = linkUrls[index];
        if (urlStr.isEmpty) return;
        WebPageRoute(url: urlStr, title: '').push(context);
      },
    );
  }
}
